package com.hxzy.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.dto.system.SysDictDataDTO;
import com.hxzy.entity.system.SysDictData;
import com.hxzy.mapper.system.SysDictDataMapper;
import com.hxzy.redis.cache.DictDataCache;
import com.hxzy.service.system.SysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 数据字典明细
 */

@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements SysDictDataService {

    @Autowired
    private DictDataCache dictDataCache;

    /**
     * SELECT dict_code,dict_label,dict_value,dict_type
     * FROM sys_dict_data
     * where  `status`='0'  and dict_type=?
     * order by dict_sort
     * 使用mybatis-plus如何来编写
     * @param dictType
     * @return
     */
    @Override
    public List<SysDictData> findByDictType(String dictType) {
        //创建查询器
        LambdaQueryWrapper<SysDictData> queryWrapper=new LambdaQueryWrapper<>();
        // and `status`='0'
        queryWrapper.eq(SysDictData::getStatus,"0");
        // and dict_type=?
        queryWrapper.eq(SysDictData::getDictType, dictType);
        //order by dict_sort
        queryWrapper.orderByAsc(SysDictData::getDictSort);

        //select dict_code,dict_label,dict_value,dict_type,list_class
        queryWrapper.select(SysDictData::getDictCode, SysDictData::getDictLabel,SysDictData::getDictValue,SysDictData::getDictType,SysDictData::getListClass);

        //返回结果
        List<SysDictData> list = this.list(queryWrapper);

        return list;
    }

    /**
     * 查询所有正常的数据
     * @return
     */
    @Override
    public List<SysDictData> findAll() {
        return this.baseMapper.findAll();
    }

    @Override
    public List<SysDictData> selectDictDataList(SysDictDataDTO sysDictDataDTO) {
        return this.baseMapper.search( sysDictDataDTO);
    }


    /**
     * 更新字典明细状态
     * @param dictCode
     * @param state
     * @return
     */
    @Override
    public boolean updateState(Long[] dictCode, String state) {
        //先查询出更新id的dict_type
        List<String> list = this.baseMapper.selectDictTypeByIds(dictCode);

        //再更新数据
        int count=super.baseMapper.updateByState(dictCode,"1");
        if(count>0){
            //更新redis缓存中的值
            for (String dictType : list){
                this.dictDataCache.rewriteDictTypeValue(dictType);
            }
        }
        return count>0;
    }


}
